<template>
	<view class="mt-2">
		<view   class="d-flex a-center border-bottom py-2 bg-white">
			<text  class="font-md text-dark px-2">
				姓名
			</text>
			<input v-model="formData.realname" type="text" placeholder="请输入姓名" placeholder-style="font-size: 30rpx;">
		</view>
		<view class="d-flex a-center border-bottom py-2 bg-white">
			<text class="font-md text-dark px-2">
				电话
			</text>
			<input v-model="formData.mobile" type="text" placeholder="请输入电话" placeholder-style="font-size: 30rpx;">
		</view>
		<view class="d-flex a-center border-bottom py-2 bg-white">
			<text class="font-md text-dark px-2">
				区域
			</text>
			<input v-model="formData.region" @click="onRegionClick" type="text" placeholder="请选择区域" placeholder-style="font-size: 30rpx;" disabled>
			<mpvueCityPicker @onConfirm="onRegionConfirm"   ref="regionPicker"></mpvueCityPicker>
		</view>
		<view class="d-flex a-center border-bottom py-2 bg-white">
			<text class="font-md text-dark px-2">
				地址
			</text>
			<input v-model="formData.detaill" type="text" placeholder="请输入详细地址" placeholder-style="font-size: 30rpx;">
		</view>
		<view class="mt-3 px-2 py-2">
			<button @click="onSubmit" type="warn" class="text-white ">
				提交
			</button>
		</view>
	</view>
</template>

<script setup>
	import mpvueCityPicker from '/components/mpvue-citypicker/mpvueCityPicker.vue';
	import { ref, reactive, onMounted} from 'vue';
	import useAddressStore from "@/stores/address.js"
  import userHttp from "../../apis/user/userHttp";
	const addressStore = useAddressStore()
	let regionPicker = ref()
  let isEdit = false;
	let formData = reactive({
		id:"",
		realname:"",
		mobile:"",
		region:"",
		detail:""
	})
	onMounted(() => {
		const address = addressStore.address
		if (address){
      isEdit = true;
			uni.setNavigationBarTitle({
			title:'编辑地址',
		})
		formData.id = address.id
		formData.realname = address.realname
		formData.mobile = address.mobile
		formData.region = address.region
		formData.detaill = address.detail
		}
		
	})
	const onRegionClick = () => {
		regionPicker.value.show()
	}
	const onRegionConfirm = (e) => {
		let address = e.label.split("-")
		let province = address[0]
		let city = address[1] == "市辖区" ?"": address[1]
		let districet= address[2]
		formData.region = province + city + districet	
		
	}
	const onSubmit = async () => {
    const address = await userHttp.createAddress(formData)
    console.log(address)
    if (isEdit) {
      uni.$emit("address-edit", {"address": formData})
    }else{
      uni.$emit("address-add", {"address": formData})
      console.log(formData);

    }
    uni.navigateBack()

	}
</script>

<style>
	       
</style>
